package cn.woo5.test.detector.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.Map;

@Slf4j
@RequestMapping("/json")
@RestController
public class JsonTestController {

    /**
     * json 中嵌套 json 字符串的情况很难看, 此方法将 json 字串转化成对象的一部分, 更容易分析嵌套部分json结构.
     * <p>
     * <p>
     * 示例:
     * <p>
     * 入参: {"msg":"成功","code":"200","data":"{\"name\":\"wang\"}"}
     * <p>
     * 扩展结果: {"msg":"成功","code":"200","data":{"name":"wang"}}
     *
     * @param json
     * @return
     */
    @ApiOperation("将json对象嵌套的json字串转化成对象的一部分, 更容易分析嵌套字串结构")
    @RequestMapping(value = "expandJsonStr", method = RequestMethod.POST)
    public Object expandJsonStr(@RequestParam String json) {
        return expandJson(json);
    }

    public Object expandJson(Object obj) {
        if (obj == null) {
            return obj;
        }
        if (obj instanceof JSONObject) {
            return expandJsonObject((JSONObject) obj);
        }
        if (obj instanceof JSONArray) {
            return expandJsonArray((JSONArray) obj);
        }
        if (obj instanceof String == false) {
            return obj;
        }
        String json = (String) obj;
        json = json.trim();
        if (json.startsWith("{")) {
            JSONObject jsonObject;
            try {
                jsonObject = JSON.parseObject(json);
            } catch (Exception exception) {
                log.error("", exception);
                return json;
            }
            return expandJsonObject(jsonObject);
        } else if (json.startsWith("[")) {
            JSONArray jsonArray;
            try {
                jsonArray = JSON.parseArray(json);
            } catch (Exception exception) {
                log.error("", exception);
                return json;
            }
            return expandJsonArray(jsonArray);
        } else {
            return json;
        }
    }

    private Object expandJsonArray(JSONArray jsonArray) {
        JSONArray result = new JSONArray();
        for (Object arrElem : jsonArray) {
            Object elem = expandJson(arrElem);
            result.add(elem);
        }
        return result;
    }

    private Object expandJsonObject(JSONObject jsonObject) {
        JSONObject result = new JSONObject();
        Map<String, Object> innerMap = jsonObject.getInnerMap();
        for (Map.Entry<String, Object> entry : innerMap.entrySet()) {
            String key = entry.getKey();
            Object valueParsed = expandJson(entry.getValue());
            result.put(key, valueParsed);
        }
        return result;
    }

    private boolean maybeJsonStr(String trimedTestStr) {
        return trimedTestStr.startsWith("{") || trimedTestStr.startsWith("[");
    }

    public static void main(String[] args) {
        // 将 {"msg":"成功","code":"200","data":"{\"name\":\"wang\"}"} 扩展为: {"msg":"成功","code":"200","data":{"name":"wang"}}
        System.out.println(new JsonTestController().expandJson("{\"code\":\"200\",\"msg\":\"成功\",\"data\": \"{\\\"name\\\":\\\"wang\\\"}\"}"));
    }
}
